package com.zt.csp.shorturl.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zt.csp.shorturl.dto.ServiceResult;
import com.zt.csp.shorturl.dto.ShortUrlDTO;
import com.zt.csp.shorturl.entity.ShortUrl;
import com.zt.csp.shorturl.service.ShortUrlService;
import com.zt.csp.shorturl.service.ViewLogService;
import com.zt.csp.shorturl.utils.StringChecker;
import com.zt.csp.shorturl.utils.ThreadLocalUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 短链接操作
 * Created by zt on 2018/4/17 0017
 */
@RestController
@RequestMapping("/api")
public class ApiController {
    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);


    @Autowired
    private ShortUrlService shortUrlService;

    @Autowired
    private ViewLogService viewLogService;

    /**
     * 生成短链接
     *
     * @param shortUrl 实体类，包含长链接
     * @return {
     * "code": 200,
     * "message": "请求成功",
     * "data": {
     * "code": "a0001k",
     * "longUrl": "https://www.test.com"
     * }
     * }
     */
    @PostMapping("/create")
    public ServiceResult create(@RequestBody ShortUrl shortUrl) {
        String longUrl = shortUrl.getLongUrl();
        ServiceResult serviceResult = StringChecker.longUrlCheck(longUrl);
        if (serviceResult.getCode() != 200) {
            return serviceResult;
        }
        return shortUrlService.getShortUrlByLongUrl(shortUrl);
    }

    /**
     * 生成短链接（给HTML页面用的，只能生成普通短链接，且有次数限制）
     *
     * @param shortUrl 实体类，包含长链接
     * @return {
     * "code": 200,
     * "message": "请求成功",
     * "data": {
     * "code": "a0001k",
     * "longUrl": "https://www.test.com"
     * }
     * }
     */
    @PostMapping("/hcreate")
    public ServiceResult hcreate(@RequestBody ShortUrl shortUrl) {
        String userId = ThreadLocalUtils.USER_THREAD_LOCAL.get();
        logger.info("userId = {}", userId);
        //todo 游客请求次数限制
        String longUrl = shortUrl.getLongUrl();
        ServiceResult serviceResult = StringChecker.longUrlCheck(longUrl);
        if (serviceResult.getCode() != 200) {
            return serviceResult;
        }
        ShortUrl shortUrlNew = new ShortUrl();
        if (!StringUtils.isEmpty(userId)) {
            shortUrlNew.setCreatedBy(userId);
        }
        shortUrlNew.setLongUrl(longUrl);
        return shortUrlService.getShortUrlByLongUrl(shortUrlNew);
    }


    /**
     * 返回长链接
     *
     * @param shortUrlCode 短链接Code
     * @return {
     * "code": 200,
     * "message": "请求成功",
     * "data": {
     * "code": "abcdef",
     * "longUrl": "http://test.passport..com/"
     * }
     * }
     */
    @GetMapping("/get/{shortUrlCode}")
    public ServiceResult get(@PathVariable String shortUrlCode) {
        ServiceResult serviceResult = shortUrlService.getLongUrlByShortUrl(shortUrlCode);
        if (serviceResult.getCode() == 200) {
            Map data = (Map) serviceResult.getData();
            data.remove("id");
        }
        return serviceResult;
    }


    /**
     * 分页获取短链接列表，需要登录。
     *
     * @param page 页码
     * @return 带页码信息的短链接列表
     */
    @GetMapping("/list")
    public ServiceResult list(@RequestParam int page) {
        EntityWrapper<ShortUrl> wrapper = new EntityWrapper<>();
        return shortUrlService.list(page, 10, wrapper);
    }

    /**
     * 删除某个短链接，软删除
     *
     * @param shortUrlDTO 短链接Code
     * @return 是否成功
     */
    @DeleteMapping("/delete")
    public ServiceResult delete(@RequestBody ShortUrlDTO shortUrlDTO) {
        // 只需要用到一个code参数
        String code = shortUrlDTO.getCode();
        if (StringUtils.isEmpty(code)) {
            return ServiceResult.NEED_PARAM;
        }
        return shortUrlService.delete(code);
    }


    @GetMapping("/log")
    public ServiceResult logList(@RequestParam int page, @RequestParam String code) {
        return viewLogService.list(page, 10, code);
    }
}
